package cn.geapi.filter.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.geapi.core.domain.bean.UserBean;
import cn.geapi.util.HttpConstraits;
import cn.geapi.util.HttpRequestUitl;
import cn.geapi.util.annotation.auth.AuthIgnore;
import cn.geapi.util.annotation.auth.AuthRedirect;

public class AuthInterceptor implements HandlerInterceptor {
	private final static Logger LOGGER = Logger
			.getLogger(AuthInterceptor.class);

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		boolean result = true;
//		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			AuthIgnore authIgnore = method.getAnnotation(AuthIgnore.class);// 忽略鉴权
			if (null != authIgnore)
				return true;
			HttpSession session = request.getSession();
			UserBean userBean = (UserBean) session
					.getAttribute(HttpConstraits.SESSION_USER);

			StringBuffer buffer = new StringBuffer(
					HttpRequestUitl.getRequestInfo(request));
			if (null == userBean) {// 没有登录
				AuthRedirect authRedirect = method// 获取请求方法重定向url
						.getAnnotation(AuthRedirect.class);
				String redUrl = authRedirect == null ? HttpConstraits.DEF_AUTH_FAILD_REDURL
						: authRedirect.value();
				buffer.append(" not login redirect to:").append(redUrl);
				response.sendRedirect(redUrl);// 重定向到登陆页
				result = false;
			} else {
				buffer.insert(0, "user:").append(userBean.toString())
						.append(" ");
				result = true;
			}
			LOGGER.info(buffer);
			return result;
//		}else{
//			return true;
//		}
	}

}
